/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.loopj.hos.image.slice;

import com.loopj.hos.image.ResourceTable;
import com.loopj.hos.image.util.MyToast;
import com.loopj.ohos.image.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.app.Context;
import ohos.bundle.IBundleManager;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;
import ohos.media.photokit.metadata.AVStorage;
import ohos.sysappcomponents.contact.ContactsCollection;
import ohos.sysappcomponents.contact.ContactsHelper;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileDescriptor;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MainAbilitySlice");
    private static final int REQUEST_CODE = 123;
    private static final int REQUEST_CODE_SECOND = 1234;
    private static final int REQUEST_ADDRESS_CODE = 10086;
    private static final int ALBUM_LENGTH_ZERO = 0;
    private static final int ALBUM_IMAGE_SIZE = 300;
    private SmartImageView smartImageView;
    private Text cacheText;
    private Text cacheNumberText;
    private Button clearBtn;
    private SmartImageView smartImageViewSecond;
    private Button clearBtnSecond;
    private Map<String, PixelMap> map = new HashMap<>();
    private ArrayList<Uri> urlList = new ArrayList<>();
    private ArrayList<PixelMap> pixelMapArrayList = new ArrayList<>();
    private Map<Integer, SmartImage> bitmapImageMap = new HashMap<>();
    private Button addressBookBtn;
    private static final String DISK_CACHE_PATH = "/web_image_cache/";

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        String[] permission = {"ohos.permission.READ_MEDIA", "ohos.permission.READ_CONTACTS"};
        requestPermissionsFromUser(permission, 0);
        WebImageCache webImageCache = new WebImageCache(this);
        webImageCache.clear();
        initView();
    }

    private void initView() {
        bitmapImageMap.put(0, new BitmapImage(getPixelMap(ResourceTable.Media_1, getContext())));
        bitmapImageMap.put(1, new BitmapImage(getPixelMap(ResourceTable.Media_2, getContext())));
        bitmapImageMap.put(2, new BitmapImage(getPixelMap(ResourceTable.Media_3, getContext())));
        bitmapImageMap.put(3, new BitmapImage(getPixelMap(ResourceTable.Media_4, getContext())));
        bitmapImageMap.put(4, new BitmapImage(getPixelMap(ResourceTable.Media_4, getContext())));
        addressBookBtn = (Button) findComponentById(ResourceTable.Id_address_book);
        addressBookBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                readContact();
            }
        });
        smartImageView = (SmartImageView) findComponentById(ResourceTable.Id_smartImage);
        cacheText = (Text) findComponentById(ResourceTable.Id_cache);
        cacheNumberText = (Text) findComponentById(ResourceTable.Id_cache_number);
        cacheNumberText.setText(getString(ResourceTable.String_image_cache_num) + openCacheImageNum(getContext()));
        smartImageViewSecond = (SmartImageView) findComponentById(ResourceTable.Id_smartImage_second);
        //获取图片路径
        TextField url = (TextField) findComponentById(ResourceTable.Id_textUrl);
        TextField urlSecond = (TextField) findComponentById(ResourceTable.Id_textUrl_second);
        findComponentById(ResourceTable.Id_selectBtn).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                displayPic(REQUEST_CODE);
            }
        });
        findComponentById(ResourceTable.Id_selectBtn_second).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                displayPic(REQUEST_CODE_SECOND);
            }
        });
        clearBtn = (Button) findComponentById(ResourceTable.Id_clearBtn);
        clearBtnSecond = (Button) findComponentById(ResourceTable.Id_clearBtn_second);
        clearBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                removeCache(url);
            }
        });
        clearBtnSecond.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                removeCache(urlSecond);
            }
        });
        findComponentById(ResourceTable.Id_confirmBtn).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                loadImage(smartImageView, url);
            }
        });
        findComponentById(ResourceTable.Id_confirmBtn_second).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                loadImage(smartImageViewSecond, urlSecond);
            }
        });
    }

    private void readContact() {
        if (verifySelfPermission("ohos.permission.READ_CONTACTS") != IBundleManager.PERMISSION_GRANTED) {
            showToast(getString(ResourceTable.String_contact_permission));
            return;
        }
        ContactsHelper con = new ContactsHelper(getContext());
        ContactsCollection contactsCollection = con.queryContacts(null, null);
        if (contactsCollection.isEmpty()) {
            showToast("please create a contact first");
        } else {
            Intent intent = new Intent();
            presentForResult(new AddressSelectAbilitySlice(contactsCollection), intent, REQUEST_ADDRESS_CODE);
        }
    }

    private void loadImage(SmartImageView smartImageView, TextField url) {
        String imageUrl = url.getText().trim();
        if (inspectEmpty(imageUrl)) {
            return;
        }
        cacheText.setText("缓存路径：" + WebImageCache.getDiskCachePath(getContext()));
        smartImageView.setBackground(null);
        smartImageView.setImageUrl(imageUrl, ResourceTable.Media_failure, ResourceTable.Media_loading,
                new SmartImageTask.OnCompleteListener() {

                    @Override
                    public void onComplete() {
                    }

                    @Override
                    public void onComplete(PixelMap bitmap) {
                        super.onComplete(bitmap);
                        loadResultToast(bitmap);
                    }
                });
    }

    private void removeCache(TextField textField) {
        String imageUrl = textField.getText().trim();
        if (inspectEmpty(imageUrl)) {
            return;
        }
        WebImage.removeFromCache(imageUrl);
        showToast("removed success");
        cacheNumberText.setText(getString(ResourceTable.String_cache_num) + openCacheImageNum(getContext()));
    }

    private void loadResultToast(PixelMap bitmap) {
        if (bitmap != null) {
            showToast(getString(ResourceTable.String_loading_success));
            cacheNumberText.setText(getString(ResourceTable.String_cache_num) + openCacheImageNum(getContext()));
        } else {
            showToast(getString(ResourceTable.String_loading_fail));
        }
    }

    private boolean inspectEmpty(String imageUrl) {
        if (imageUrl == null || imageUrl.equals("")) {
            showToast("address cannot be empty");
            return true;
        }
        return false;
    }

    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        super.onResult(requestCode, resultIntent);
        try {
            if (null != resultIntent) {
                String url = resultIntent.getStringParam("picture_res_id");
                BitmapImage bitmapImage = new BitmapImage(map.get(url));
                if (requestCode == REQUEST_CODE) {
                    smartImageView.setBackground(null);
                    smartImageView.setImage(bitmapImage);
                } else if (requestCode == REQUEST_ADDRESS_CODE) {
                    smartImageView.setBackground(null);
                    int position = resultIntent.getIntParam("addressId", 0);
                    smartImageView.setImage(bitmapImageMap.get(position));
                } else {
                    smartImageViewSecond.setBackground(null);
                    smartImageViewSecond.setImage(bitmapImage);
                }
                showToast(getString(ResourceTable.String_loading_success));
                cacheText.setText(getString(ResourceTable.String_no_cache_required));
            }
        } catch (Exception e) {
            HiLog.debug(label, "onResult" + e.getMessage());
        }
    }

    private void showToast(String message) {
        MyToast.show(this, message, MyToast.ToastLayout.BOTTOM);
    }

    private PixelMap getPixelMap(long resId, Context context) {
        InputStream drawableInputStream = null;
        try {
            drawableInputStream = context.getResourceManager().getResource((int) resId);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = "image/png";
            ImageSource imageSource = ImageSource.create(drawableInputStream, null);
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.desiredSize = new Size(0, 0);
            decodingOptions.desiredRegion = new Rect(0, 0, 0, 0);
            decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
            PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
            return pixelMap;
        } catch (Exception e) {
            HiLog.debug(label, "getPixelMap" + e.getMessage());
        } finally {
            try {
                if (drawableInputStream != null) {
                    drawableInputStream.close();
                }
            } catch (Exception e) {
                HiLog.debug(label, "getPixelMap" + e.getMessage());
            }
        }
        return null;
    }

    public void displayPic(int code) {
        if (verifySelfPermission("ohos.permission.READ_MEDIA") != IBundleManager.PERMISSION_GRANTED) {
            showToast(getString(ResourceTable.String_album_permissions));
            return;
        }
        DataAbilityHelper helper = DataAbilityHelper.creator(getContext());
        try {
            ResultSet result = helper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, null, null);
            if (result == null) {
                return;
            }
            if (result.getRowCount() == ALBUM_LENGTH_ZERO) {
                showToast(getString(ResourceTable.String_album_length_zero));
                return;
            }
            if (result.getRowCount() == map.size()) {
                Intent intent_picture_select = new Intent();
                presentForResult(new PictureSelectAbilitySlice(pixelMapArrayList, urlList), intent_picture_select, code);
                return;
            }
            while (result.goToNextRow()) {
                int mediaId = result.getInt(result.getColumnIndexForName(AVStorage.Images.Media.ID));
                Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, "" + mediaId);
                FileDescriptor filedesc = helper.openFile(uri, "r");
                ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
                decodingOpts.desiredSize = new Size(ALBUM_IMAGE_SIZE, ALBUM_IMAGE_SIZE);
                ImageSource imageSource = ImageSource.create(filedesc, null);
                PixelMap pixelMap = imageSource.createThumbnailPixelmap(decodingOpts, true);
                if (!map.containsKey(uri.toString())) {
                    pixelMapArrayList.add(pixelMap);
                    urlList.add(uri);
                    map.put(uri.toString(), pixelMap);
                }
            }
            Intent intent_picture_select = new Intent();
            presentForResult(new PictureSelectAbilitySlice(pixelMapArrayList, urlList), intent_picture_select, code);
        } catch (Exception e) {
            HiLog.debug(label, "getPixelMap" + e.getMessage());
        }
    }

    private int openCacheImageNum(Context context) {
        Context appContext = context.getApplicationContext();
        String diskCachePath = appContext.getCacheDir().getAbsolutePath() + DISK_CACHE_PATH;
        //传入指定文件夹的路径
        File file = new File(diskCachePath);
        File[] files = file.listFiles();
        if (null != files) {
            return files.length;
        }
        return 0;
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
